<template>
  <div class="news-wall" ref="newsWall">
    <!-- 循环渲染每个新闻组 -->
    <div v-for="(group, groupIndex) in newsList" :key="groupIndex" class="news-group">
      <!-- 显示每个组的头部标题 -->
      <div v-if="group.header" class="news-wall-header">
        <span>{{ group.header }}</span>
      </div>

      <!-- 新闻组内的新闻列表 -->
      <div class="news-list" :style="newsListStyle">
        <div
          v-for="(item, index) in group.news"
          :key="index"
          class="news-item"
          @click="handleNewsClick(item.url)"
        >
          <!-- 判断icon是否是组件 -->
          <component v-if="typeof item.icon === 'object'" :is="item.icon" class="news-icon" />
          <!-- 如果icon是字符串（即路径），用el-image加载 -->
          <el-image v-else :src="item.icon" class="news-icon" fit="cover" :alt="item.news" />
          <span class="news-title">{{ item.news }}</span>
        </div>
      </div>
    </div>

    <!-- 更多按钮 -->
    <el-button
      v-if="showMoreButton"
      type="primary"
      class="more-button"
      @click="handleMoreClick"
      size="small"
      link
    >
      <span v-if="ExpandMode === 'Expand' && !expanded">更多</span>
      <span v-if="ExpandMode === 'Expand' && expanded">收起</span>
      <span v-if="ExpandMode === 'Link'">更多</span>
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'NewsWall',
  props: {
    newsList: {
      type: Array,
      required: true,
      default: () => []
    },
    ExpandMode: {
      type: String,
      default: 'Expand',
      validator: (value) => ['Expand', 'Link'].includes(value)
    }
  },
  data() {
    return {
      expanded: false, // 控制是否展开
      maxVisibleItems: 3, // 初始显示的最大新闻条数
      showMoreButton: false, // 控制“更多”按钮是否显示
      newsListStyle: {
        'max-height': '250px', // 限制列表的最大高度
        'overflow-y': 'auto' // 启用滚动条
      }
    }
  },
  methods: {
    handleMoreClick() {
      if (this.ExpandMode === 'Expand') {
        this.expanded = !this.expanded
        this.newsListStyle['max-height'] = this.expanded ? 'none' : '250px' // 动态调整高度
      } else if (this.ExpandMode === 'Link') {
        this.$emit('link-click')
      }
    },
    handleNewsClick(url) {
      if (url) {
        if (/^(http|https):/.test(url)) {
          window.open(url, '_blank')
        } else {
          this.$router.push(url)
        }
      }
    }
  }
}
</script>

<style scoped>
.news-group {
  margin-bottom: 8px;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.news-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 1px 0;
  transition: background-color 0.3s;
}

.news-item:hover {
  background-color: #f0f8ff;
}

.news-icon {
  width: 25px;
  height: 25px;
  margin-right: 6px;
  border-radius: 4px;
}

.news-title {
  font-size: 14px;
  color: #333;
  flex: 1;
}

.more-button {
  display: block;
  width: 100%;
  text-align: center;
  margin-top: 8px;
  color: #1e90ff;
}

.more-button:hover {
  color: #1c86ee;
}
</style>
